package com.shbaiche.bifenba.ui.my;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.Event;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.user.LoginMessage;
import com.shbaiche.bifenba.model.user.LoginType;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;
import com.shbaiche.bifenba.util.UserUtil;
import com.shbaiche.bifenba.view.CountButton;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroid.event.BusFactory;
import cn.droidlover.xdroidbase.router.Router;
import okhttp3.Call;


public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_back)
    ImageView back;

    @BindView(R.id.login_account)
    EditText account;

    @BindView(R.id.login_val)
    EditText val;

    @BindView(R.id.login_val_text)
    CountButton valTxt;

    @BindView(R.id.login_btn)
    Button login;

    @BindView(R.id.login_agreement)
    TextView agreemet;

    @BindView(R.id.login_qq)
    ImageView qq;
    @BindView(R.id.login_wb)
    ImageView wb;
    @BindView(R.id.login_wx)
    ImageView wx;

    private Dialog dg;

    /**
     * 微信登录相关
     */
    private IWXAPI api;

    public static String WXStartStr = "";

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(WXStartStr)) {
            dg.show();
            try {
                JSONObject jsonObject = new JSONObject(WXStartStr);


                OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/access_token")
                        .addParams("appid", "wxc5ed67172ab270e5")
                        .addParams("secret", "4ea82d7078383fe365e87a32c4aa4c4a")
                        .addParams("code", jsonObject.getString("code"))
                        .addParams("grant_type", "authorization_code")
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(okhttp3.Call call, Exception e, int id) {
                                dg.hide();
                                ToastUtil.show("请求超时！");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                try {
                                    JSONObject obj = new JSONObject(response);

                                    LoginMessage msg = new LoginMessage();
                                    msg.setUserId(obj.getString("openid"));
                                    msg.setLoginType(LoginType.WX_LOGIN);

                                    NetApi.login(msg, new JsonCallback<TransMessage>() {

                                        @Override
                                        public void onFail(Call call, Exception e, int id) {
                                            dg.hide();
                                            ToastUtil.show("登录失败！" + e.getMessage());
                                        }

                                        @Override
                                        public void onError(Call call, Exception e, int id) {
                                            dg.hide();
                                            ToastUtil.show("登录失败！" + e.getMessage());
                                        }

                                        @Override
                                        public void onResponse(TransMessage response, int id) {
                                            dg.hide();
                                            Gson gson = new Gson();
                                            LoginMessage msg = gson.fromJson(response.getMessage(), LoginMessage.class);
                                            if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                                                App.setPassport(msg.getPassport());

                                                BusFactory.getBus().post(new Event.LoginEvent(msg.getPassport()));
                                                new UserUtil().register();
                                                ToastUtil.show("登录成功!");
                                                finish();
                                            } else {
                                                ToastUtil.show("登录失败！" + response.getMessage());
                                            }
                                        }
                                    });
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
            } catch (Exception e) {

            }
        }
        WXStartStr = "";
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            //让应用主题内容占用系统状态栏的空间,注意:下面两个参数必须一起使用 stable 牢固的
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //设置状态栏颜色为透明
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        dg = new Dialog(this);
        dg.setContentView(R.layout.view_loading);

        valTxt.setDefaultTime(60 * 1000);

        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, "wxc5ed67172ab270e5", true);
        //将应用的appid注册到微信
        api.registerApp("wxc5ed67172ab270e5");
    }


    @Override
    public void setListener() {

    }

    @OnClick({
            R.id.login_back,
            R.id.login_val_text,
            R.id.login_btn,
            R.id.login_agreement,
            R.id.login_qq,
            R.id.login_wb,
            R.id.login_wx,
    })
    public void clickEvent(View view) {
        switch (view.getId()) {

            case R.id.login_back:

                finish();
                break;
            case R.id.login_val_text: {
                if (TextUtils.isEmpty(account.getText().toString())) {
                    ToastUtil.show("手机号码不能为空！");
                    return;
                }

                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Activity.INPUT_METHOD_SERVICE);
                if (val != null) {
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(val.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }

                LoginMessage msg = new LoginMessage();
                msg.setMobile(account.getText().toString());
                msg.setVerifyType(LoginMessage.VerifyType.VALIDMOBILE);
                dg.show();

                NetApi.sendSms(msg, new JsonCallback<TransMessage>() {

                    @Override
                    public void onFail(Call call, Exception e, int id) {
                        ToastUtil.show("验证码发送失败!");
                        dg.hide();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show("onFail" + e.getMessage());
                        dg.hide();
                    }

                    @Override
                    public void onResponse(TransMessage response, int id) {
                        dg.hide();
                        Gson gson = new Gson();
                        LoginMessage login = gson.fromJson(response.getMessage(), LoginMessage.class);
                        if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, login.getCode())) {
                            ToastUtil.show(login.getMessage());
                        } else {
                            ToastUtil.show("验证码发送失败" + login.getMessage());
                        }
                    }
                });
            }
            break;
            case R.id.login_btn:
                if (TextUtils.isEmpty(account.getText().toString())) {
                    ToastUtil.show("手机号码不能为空！");
                    return;
                }
                if (TextUtils.isEmpty(val.getText().toString())) {
                    ToastUtil.show("验证码不能为空！");
                    return;
                }

                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Activity.INPUT_METHOD_SERVICE);
                if (account != null) {
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(account.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }

                LoginMessage msg = new LoginMessage();
                msg.setMobile(account.getText().toString());
                msg.setVerifyCode(val.getText().toString());
                msg.setLoginName(account.getText().toString());
                msg.setLoginType(LoginType.LOGIN);
                dg.show();

                NetApi.login(msg, new JsonCallback<TransMessage>() {

                    @Override
                    public void onFail(Call call, Exception e, int id) {
                        dg.hide();
                        ToastUtil.show("登录失败！" + e.getMessage());
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dg.hide();
                        ToastUtil.show("登录失败！" + e.getMessage());
                    }

                    @Override
                    public void onResponse(TransMessage response, int id) {
                        dg.hide();
                        Gson gson = new Gson();
                        LoginMessage msg = gson.fromJson(response.getMessage(), LoginMessage.class);
                        if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                            App.setPassport(msg.getPassport());

                            BusFactory.getBus().post(new Event.LoginEvent(msg.getPassport()));

                            ToastUtil.show("登录成功!");
                            finish();
                        } else {
                            ToastUtil.show("登录失败！" + response.getMessage());
                        }
                    }
                });
                break;
            case R.id.login_agreement:
                break;
            case R.id.login_qq:
                break;
            case R.id.login_wb:
                break;
            case R.id.login_wx:
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";//
//                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
                req.state = "wechat_sdk_微信登录";
                api.sendReq(req);
                break;

        }
    }

    public static void launch(Activity activity) {
        Router.newIntent(activity)
                .to(LoginActivity.class)
                .data(new Bundle())
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.login;
    }


    @Override
    public void setToolbar() {

    }

    @Override
    protected void onDestroy() {
        if (dg != null) {
            dg.dismiss();
            dg = null;
        }
        super.onDestroy();
    }
}
